import time
import threading
import pynput

from json import loads,dumps
from threading import Event

import optimization
from uses_pynput import record
from uses_pynput import play

done:Event

def set_done(): done.set()

def read_settings()->dict:
    with open('settings.json','r')as file:
        return loads(file.read())

settings=read_settings()

def terminal_record():
    global done
    print(f'开始录制({settings['stop']}结束)')
    done = Event()
    filename = 'saves\\' + time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time())) + '.jrec'
    t = threading.Thread(target=record.start_record, args=(filename, done))
    with pynput.keyboard.GlobalHotKeys({settings['stop']: set_done}) as h:
        t.start()
        t.join()
        h.stop()
    print(f'\r\033[32m录制完成，已存储至文件：{filename}\033[0m')

def terminal_play():
    filename = input('请输入要播放的文件名：')
    if filename=='':return
    filename = 'saves\\' + filename
    if not filename.endswith('.jrec'):
        filename+='.jrec'
    print(f'开始播放({settings['stop']}强行停止)')
    done = Event()
    with pynput.keyboard.GlobalHotKeys({settings['stop']: set_done}) as h:
        t = threading.Thread(target=play.start_play, args=(filename, done))
        t.start()
        t.join()
        h.stop()
        if done.is_set():print('\033[31m播放已终止\033[0m')
        else:print('\r\033[32m播放完成\033[0m')

def terminal_optimize():
    filename = input('请输入文件名：')
    if filename=='':return
    filename = 'saves\\' + filename
    file = open(filename, 'r')
    data = [loads(line) for line in file.readlines()]
    file.close()
    try:
        min_time = input('请输入move的最小时间(空为0.02):')
        min_time = 0.02 if min_time == '' else float(min_time)
        length = input('请输入time的小数位数(空为4):')
        length = 4 if length == '' else int(length)
    except ValueError:
        print('\033[31m输入格式不正确！\033[0m\n')
        return
    data = optimization.optimize_move(data, min_time)
    data = optimization.optimize_time(data, length)
    filename_list = filename.split('.')
    filename_list[-2] += '_opt'
    filename = '.'.join(filename_list)
    file = open(filename, 'w+')
    for line in data:file.write(dumps(line) + '\n')
    file.close()
    print(f'\033[32m优化完成，输出至:{filename}\033[0m')

def on_pass():pass

def terminal_set_settings():
    global settings
    new_stop=input(f'请手动输入新的停止快捷键(注意不是按下；示例：<ctrl_l>+<f1>或<ctrl>+<alt>+h)\033[32m(当前:{settings['stop']}):')
    if new_stop=='':return
    print('正在测试，请稍后...')
    try:
        test_hotkey=pynput.keyboard.GlobalHotKeys({new_stop:on_pass})
        test_hotkey.stop()
    except ValueError:
        print('\033[31m输入的值不合规，未保存！\033[0m')
    else:
        settings={'stop':new_stop}
        with open('settings.json','w+')as file:
            file.write(dumps(settings))
        print('\033[32m设置成功\033[0m')

def terminal_2_get_information():return f'\n请选择要进行的操作({settings['record']}-录制 | {settings['play']}-播放 | {settings['optimize']}-优化 | {settings['set_settings']}-设置 | {settings['exit']}-退出):'

def terminal_2_set_settings():
    global settings
    what_to_change=input('请输入要修改的快捷键(1-录制 2-播放 3-优化 4-设置 5-退出 6-停止):')
    if len(what_to_change)!=1 or what_to_change not in '123456':
        print('\033[31m输入的值不合规\033[0m')
        return
    value=input('请输入的新的值:')
    
    try:
        test_hotkey=pynput.keyboard.GlobalHotKeys({value:on_pass})
        test_hotkey.stop()
    except ValueError:
        print('\033[31m输入的值不合规，未保存！\033[0m')
    else:
        match what_to_change:
            case '1':
                settings['record']=value
            case '2':
                settings['play']=value
            case '3':
                settings['optimize']=value
            case '4':
                settings['set_settings']=value
            case '5':
                settings['exit']=value
            case '6':
                settings['stop']=value
        with open('settings.json','w+')as file:
            file.write(dumps(settings))
        print('\033[32m设置成功\033[0m')